package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        // 1.查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        // 2.查询blog有关的用户
        queryBlogUser(blog);
        // 3.判断当前blog是否被用户点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result blogLike(Long id) {

        //1.获取到当前用户id
        Long userId = UserHolder.getUser().getId();
        //1.2设置key
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //2.判断用户是否点赞过
        Double isLiked = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        if (isLiked == null) {
            //2.1.1未点赞，数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                //2.1.2向redis存入点赞用户列表
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //2.2.1点赞过,取消点赞，数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                //2.2.2将redis删除点赞用户记录
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.设置key
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //从redis中查询出前五点赞的用户
        Set<String> UserStrs = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (UserStrs == null || UserStrs.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //将用户解析为用户id集合
        List<Long> userIds = UserStrs.stream().map(Long::valueOf).collect(Collectors.toList());
        String UserStr = StrUtil.join(",", userIds);
        //将id集合转为UserDTO
        List<UserDTO> userDTOList = userService.query()
                .in("id", userIds).last("ORDER BY FIELD(id," + UserStr + ")").list()
                .stream()
                .map(userDO -> BeanUtil.copyProperties(userDO, UserDTO.class))
                .collect(Collectors.toList());

        //返回UserDTO集合
        return Result.ok(userDTOList);
    }


    /**
     * 发布blog后推送到粉丝的收件箱
     *
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.保存blog到数据库
        blog.setUserId(userId);
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            //新增失败，返回错误信息
            return Result.fail("保存博客失败");

        }
        //3.将blog推送到用户粉丝的收件箱
        //3.1获取该用户的粉丝ids
        List<Follow> followList = followService.query().eq("follow_user_id", userId).list();
        for (Follow follow : followList) {
            //3.2向每一个粉丝的收件箱推送blog
            Long fansId = follow.getUserId();
            String key = "feeds：" + fansId;
            //3.3创建redis中的sortedSet存放收件箱,score值为时间戳
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }

        //4，返回blogId
        return Result.ok(blog.getId());
    }


    /**
     * 查询关注的博客
     *
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryFollowBlogs(Long max, Integer offset) {
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        //2.查询用户的收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        ArrayList<Long> ids = new ArrayList<>();
        long minTime = 0;
        int offSet = 1;
        //2.1遍历redis中的集合  解析出blogIds、minTime、offset
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String blogId = typedTuple.getValue();
            ids.add(Long.valueOf(blogId));
            //判断遍历到的是否等于minTime
            long mt = typedTuple.getScore().longValue();
            if (mt == minTime) {
                offSet++;
            } else {
                //若不为最小的，则更新minTime,偏移量重置
                minTime = mt;
                offSet = 1;
            }
        }
        //3.根据ids查询出blogs
        //3.1ids转为idStr
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = this.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        //4.查询blog有关的用户、是否点过赞
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(offSet);
        scrollResult.setMinTime(minTime);
        //4.封装并返回
        return Result.ok(scrollResult);
    }

    private void isBlogLiked(Blog blog) {
        //1.1设置value
        Long userId = UserHolder.getUser().getId();
        if (userId == null) {
            return;
        }
        //1.2设置key
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        //2. redis中查询是否点过赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null) {
            blog.setIsLike(true);
        }
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        isBlogLiked(blog);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
